//
//  Me2DayOAuthResult.m
//  CairnStory
//  www.cairnstory.com
//
//  Created by saturna on 11. 3. 18..
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "Me2DayOAuthResult.h"
#import "NSString+MD5.h"

#define kTokenKey @"token"
#define kUserIdKey @"user_id"
#define kUserKeyKey @"user_key"
#define kResultKey @"result"


@implementation Me2DayOAuthResult

@synthesize token = m_token;
@synthesize userId = m_userId;
@synthesize userKey = m_userKey;
@synthesize appKey = m_appKey;
@synthesize isAuthorized = m_isAuthorized;


- (id)initWithDictionary:(NSDictionary*)auth andAppKey:(NSString*)appKey
{
	self = [super init];
	if (self == nil)
	{
		return self;
	}

	if (auth != nil)
	{
		m_token = [[auth objectForKey:kTokenKey] retain];
		m_userId = [[auth objectForKey:kUserIdKey] retain];
		m_userKey = [[auth objectForKey:kUserKeyKey] retain];
		m_isAuthorized = [[auth objectForKey:kResultKey] isEqualToString:@"true"];
	}
	m_appKey = [appKey retain];

	return self;
}

- (void)dealloc
{
	[m_token release];
	[m_userId release];
	[m_userKey release];
	[m_appKey release];
	[m_ukey release];

	[super dealloc];
}


- (NSString*)description
{
	return [NSString stringWithFormat:@"<%@> {\n"
			"	token : %@;\n"
			"	userId : %@;\n"
			"	userKey : %@;\n"
			"	isAuthorized : %d;\n"
			"	appKey : %@;\n"
			"	ukey : %@"
			"}",
			[self class],
			m_token,
			m_userId,
			m_userKey,
			m_isAuthorized,
			m_appKey,
			m_ukey];
}

- (NSString*)generateUKey
{
	if (m_ukey != nil)
	{
		return m_ukey;
	}

	// 참고 : http://dev.naver.com/openapi/apis/me2day/me2api_intro#metwo3
	// nonce + md5 (nonce + user_key)
	// --> nonce : 임의로 생성된 16진수 문자열

	int nonce = (11111111 + arc4random() % (99999999-11111111+1));
	NSData* nonceData = [NSData dataWithBytes:&nonce length:sizeof(nonce)];

	NSMutableString* nonceBuffer = [[NSMutableString alloc] init];
	const unsigned char* dataBuffer = [nonceData bytes];

	for (int i=0; i < [nonceData length]; ++i)
	{
		[nonceBuffer appendFormat:@"%02X", (unsigned long)dataBuffer[i]];
	}
	//if (DEBUG) Me2Log(@"==> nonce : [%@] / %d", nonceBuffer, [nonceBuffer length]);

	NSString* ukey = [[nonceBuffer stringByAppendingString:self.userKey] md5];
	ukey = [nonceBuffer stringByAppendingString:ukey];
	[nonceBuffer release];

	m_ukey = [ukey retain];
	return m_ukey;
}

@end
